package com.atguigu.bigdata.chapter11.sql;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/9/9 14:09
 */
public class Flink01_SQL_BaseUse {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1000L, 10),
            new WaterSensor("sensor_2", 2000L, 20),
            new WaterSensor("sensor_1", 3000L, 30),
            new WaterSensor("sensor_1", 4000L, 40),
            new WaterSensor("sensor_2", 6000L, 50),
            new WaterSensor("sensor_1", 7000L, 60),
            new WaterSensor("sensor_1", 8000L, 80)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        
        // flink 提供了两个key执行SQL的方法:
        // 1. executeSQL
        //        tEnv.executeSql("只能执行DDL语句和增删改(DML)")
        // 2. sqlQuery
        //        tEnv.sqlQuery("这个只能执行查询语句")
        
        // 对表执行查询的时候, 有两种查询方式:
        // 1. 查询未注册的表: 把Table直接拼接在需要表名的地方
        //Table result = tEnv.sqlQuery("select * from " + table);
       // result.execute().print();
        
        // 2. 查询已注册的表(建议使用): 先注册一个临时表, 有了一个表名, 然后进行查询
        tEnv.createTemporaryView("sensor", table);
        tEnv.sqlQuery("select * from sensor where id='sensor_1'").execute().print();
        
        
    }
}
